package com.example.fill.Test240126;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Transaction implements Rec,Emi {

    Emitter emi;
    Rec rec;
    IOManager ioManager;
    Random random = new Random();
    ExecutorService executorService = Executors.newSingleThreadExecutor();

    public Transaction(Listener listener) {
        ioManager = new IOManager(listener);
        this.emi = new Emitter(this);
        this.rec = new Receiver(this);
    }

    @Override
    public void receive(byte[] b, UUID uuid) {
        System.out.println(uuid.toString() + "收到回复");
        ioManager.receiveCommend(b,uuid);
    }

    @Override
    public void send(byte[] b, UUID uuid) {
        UUID uuid1 = UUID.randomUUID();
        Commend commend = new Commend()
                .setToken(uuid1)
                .setPushTime(System.currentTimeMillis())
                .setPushData(null);
        ioManager.putCommend(commend);
        emi.receive(null,uuid1);
    }

    public void start(){
        executorService.submit((Runnable) () -> {
            while (true){
                try {
                    Thread.sleep(random.nextInt(1000));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("发送请求"+System.currentTimeMillis());
                send(null,null);
            }
        });
    }
}
